這個例子中,匿名函式會存取外部函式中的 originPrice,並保存其狀態。當呼叫 breadPrice 時,會以 originPrice 為基礎計算回傳值:
function discountTool(price) {
const originPrice = price;
return function (value) {
return originPrice * value;
};
}
const breadPrice = discountTool(100);
console.log(breadPrice(0.7)); // 70
函式可以作為參數來傳遞
const arr = ["小明", "杰倫", "漂亮阿姨"];
// 等同於使用原生 forEach 方法
function fn(arr, callbackFunction) {
for (let index = 0; index < arr.length; index++) {
const element = arr[index];
callbackFunction(element, index);
}
}
fn(arr, function (item, i) {
console.log(item, i);
});
arr.forEach((item, i) => {
console.log(item, i);
});
函式可以作為回傳值
function fn() {
return function () {
console.log("這是回傳的函式");
};
}
fn()();
參考資料
(https://hackmd.io/@hexschool/rkEOZSJSi)